<script>
import { batchDelete, page, update } from '@/api/question';
import { listQuestionBank } from '@/api/questionBank';

export default {
    components: {
        Button: () => import('primevue/button'),
        InputText: () => import('primevue/inputtext'),
        InputNumber: () => import('primevue/inputnumber'),
        Dropdown: () => import('primevue/dropdown'),
        Dialog: () => import('primevue/dialog'),
        Toast: () => import('primevue/toast'),
        Toolbar: () => import('primevue/toolbar'),
        ScrollPanel: () => import('primevue/scrollpanel'),
        Avatar: () => import('primevue/avatar'),
        Tag: () => import('primevue/tag')
    },
    data() {
        return {
            question: {
                id: null,
                questionNumber: 1,
                content: '',
                options: [],
                questionBankId: null,
                type: 0,
                correctAnswer: '',
                explanation: '',
                discussion: [],
                status: 1,
                optionsEn: [],
                contentEn: '',
                explanationEn: '',
                url:''
            },
            questionBanks: [],
            saving: false,
            deleteDialog: false,
            questionTypes: [
                { label: '单选题', value: 0 },
                { label: '多选题', value: 1 }
            ],
            statusOptions: [
                { label: '启用', value: 1 },
                { label: '禁用', value: 0 }
            ]
        };
    },
    computed: {
        isNew() {
            return !this.$route.params.id;
        },
        // parsedOptions: {
        //     get(){
        //         try {
        //             console.log(this.question.options);
        //             let parse = JSON.parse(this.question.options || '[]');
        //             return parse
        //         } catch (e) {
        //             console.error('解析选项失败:', e);
        //             return [];
        //         }
        //     },
        //     set(value) {
        //         this.question.options = JSON.stringify(value);
        //         console.log(this.question.options);
        //     }
        // },
        // parsedDiscussions() {
        //     try {
        //         console.log(this.question.discussion);
        //         return JSON.parse(this.question.discussion || '[]');
        //     } catch (e) {
        //         console.error('解析选项失败:', e);
        //         return [];
        //     }
        // }
    },
    methods: {
        getInitials(username) {
            if (!username) return '?';
            return username.charAt(0).toUpperCase();
        },
        async loadQuestion() {
            if (this.isNew) return;

            try {
                const response = await page({
                    pageNum: 1,
                    pageSize: 1,
                    id: this.$route.params.id
                });
                if (response.code === 200 && response.data.list && response.data.list.length > 0) {
                    this.question = response.data.list[0];
                    try {
                        this.question.options = JSON.parse(this.question.options || '[]');
                        this.question.optionsEn = JSON.parse(this.question.optionsEn || '[]');
                    } catch (e) {
                        /* empty */
                    }
                    try {
                        // this.question.discussion = JSON.parse(this.question.discussion || '[]');
                    } catch (e) {
                        /* empty */
                    }
                } else {
                    this.$toast.add({
                        severity: 'error',
                        summary: '加载失败',
                        detail: '无法加载题目数据',
                        life: 3000
                    });
                }
                console.log('题目数据:', this.question);
            } catch (error) {
                console.error('加载题目失败:', error);
                this.$toast.add({
                    severity: 'error',
                    summary: '加载失败',
                    detail: '无法加载题目数据',
                    life: 3000
                });
            }
        },
        async loadQuestionBanks() {
            try {
                const response = await listQuestionBank({
                    pageNum: 1,
                    pageSize: 1000
                });
                if (response.code === 200) {
                    this.questionBanks = response.data || [];
                }
            } catch (error) {
                console.error('加载题库失败:', error);
            }
        },
        async saveQuestion() {
            this.question.options = JSON.stringify(this.question.options);
            this.question.optionsEn = JSON.stringify(this.question.optionsEn);
            console.log(this.question);
            this.saving = true;
            try {
                const response = await update(this.question);
                if (response.code === 200) {
                    this.$toast.add({
                        severity: 'success',
                        summary: '成功',
                        detail: '题目保存成功',
                        life: 3000
                    });
                    this.$router.go(0);
                } else {
                    this.$toast.add({
                        severity: 'error',
                        summary: '保存失败',
                        detail: response.message || '保存题目失败',
                        life: 3000
                    });
                }
            } catch (error) {
                console.error('保存题目失败:', error);
                this.$toast.add({
                    severity: 'error',
                    summary: '保存失败',
                    detail: '保存题目失败',
                    life: 3000
                });
            } finally {
                this.saving = false;
            }
        },
        async deleteQuestion() {
            try {
                const response = await batchDelete(this.question.id);
                if (response.code === 200) {
                    this.$toast.add({
                        severity: 'success',
                        summary: '成功',
                        detail: '题目删除成功',
                        life: 3000
                    });
                    this.$router.back();
                } else {
                    this.$toast.add({
                        severity: 'error',
                        summary: '删除失败',
                        detail: response.message || '删除题目失败',
                        life: 3000
                    });
                }
            } catch (error) {
                console.error('删除题目失败:', error);
                this.$toast.add({
                    severity: 'error',
                    summary: '删除失败',
                    detail: '删除题目失败',
                    life: 3000
                });
            } finally {
                this.deleteDialog = false;
            }
        },
        getRandomColor() {
            const colors = [
                '#FF5733', // Red
                '#33FF57', // Green
                '#3357FF', // Blue
                '#FF33A1', // Pink
                '#FF8C33', // Orange
                '#33FFF5', // Cyan
                '#8C33FF', // Purple
                '#FFD700' // Gold
            ];
            return colors[Math.floor(Math.random() * colors.length)];
        },
        addOption(language) {
            if (language === 0) {
                const newOption = {
                    label: String.fromCharCode(65 + this.question.options.length),
                    content: ''
                };
                this.question.options = [...this.question.options, newOption];
            }else {
                const newOption = {
                    label: String.fromCharCode(65 + this.question.optionsEn.length),
                    content: ''
                };
                this.question.optionsEn = [...this.question.optionsEn, newOption];
            }
        },
        removeOption(index,language) {
            if (language === 0) {
                this.question.options = this.question.options.filter((_, i) => i !== index);
            }else {
                this.question.optionsEn = this.question.optionsEn.filter((_, i) => i !== index);
            }
        },
        goBack() {
            this.$router.back();
        },
        confirmDelete() {
            this.deleteDialog = true;
        }
    },
    mounted() {
        this.loadQuestion();
        this.loadQuestionBanks();
    }
};
</script>

<template>
    <div class="card">
        <Toast />
        <Toolbar class="mb-4">
            <template #start>
                <Button label="返回" icon="pi pi-arrow-left" severity="secondary" @click="goBack" class="p-button-rounded" />
            </template>
            <template #end>
                <div class="flex gap-2">
                    <!--                    <Button v-if="!isNew" label="删除" icon="pi pi-trash" severity="danger" @click="confirmDelete" />-->
                    <Button label="保存" icon="pi pi-save" @click="saveQuestion" :loading="saving" />
                </div>
            </template>
        </Toolbar>

        <div class="grid">
            <!-- 左侧题目内容区域 -->
            <div class="col-12 lg:col-8">
                <Splitter>
                    <SplitterPanel class="flex flex-col px-4 justify-center">
                        <div class="mb-4">
                            <h5 class="mb-2">题目内容</h5>
                            <Textarea v-model="question.content" rows="5" cols="20" fluid />
                        </div>

                        <div class="mb-4">
                            <h5 class="mb-2">选项</h5>
                            <div v-for="(option, index) in question.options" :key="index" class="mb-3">
                                <div class="flex align-items-center gap-2 mb-2">
                                    <InputText v-model="option.label" class="w-10" />
                                    <Button icon="pi pi-trash" text rounded severity="danger" @click="removeOption(index,0)" />
                                </div>
                                <Textarea v-model="option.content" rows="3" cols="20" fluid />
                            </div>
                            <Button label="添加选项" icon="pi pi-plus" class="p-button-outlined" @click="addOption(0)" />
                        </div>

                        <div class="mb-4">
                            <h5 class="mb-2">解释</h5>
                            <Textarea v-model="question.explanation" rows="10" cols="20" fluid />
                        </div>
                    </SplitterPanel>
                    <SplitterPanel class="flex flex-col px-4 justify-center">
                        <div class="mb-4">
                            <h5 class="mb-2">英文题目内容</h5>
                            <Textarea v-model="question.contentEn" rows="5" cols="20" fluid />
                        </div>

                        <div class="mb-4">
                            <h5 class="mb-2">英文选项</h5>
                            <div v-for="(option, index) in question.optionsEn" :key="index" class="mb-3">
                                <div class="flex align-items-center gap-2 mb-2">
                                    <InputText v-model="option.label" class="w-10" />
                                    <Button icon="pi pi-trash" text rounded severity="danger" @click="removeOption(index,1)" />
                                </div>
                                <Textarea v-model="option.content" rows="3" cols="20" fluid />
                            </div>
                            <Button label="添加选项" icon="pi pi-plus" class="p-button-outlined" @click="addOption(1)" />
                        </div>

                        <div class="mb-4">
                            <h5 class="mb-2">英文解释</h5>
                            <Textarea v-model="question.explanationEn" rows="10" cols="20" fluid />
                        </div>
                    </SplitterPanel>
                </Splitter>
                <div class="card">
                    <div class="mb-4">
                        <h5 class="mb-2">讨论</h5>
                        <ScrollPanel style="height: 300px" class="border-1 border-round">
                            <div v-if="this.question.discussion.length === 0" class="p-4 text-center text-color-secondary">暂无讨论</div>
                            <div v-else class="p-4">
                                <div v-for="(discussion, index) in parsedDiscussions" :key="index" class="mb-4">
                                    <div class="flex gap-3">
                                        <Avatar :label="getInitials(discussion.username)" style="background-color: #ece9fc; color: #2a1261" />
                                        <div class="flex-1">
                                            <div class="flex align-items-center gap-2 mb-2">
                                                <span class="font-bold">{{ discussion.username }}</span>
                                                <Tag :value="discussion.answer" severity="info" />
                                            </div>
                                            <div class="text-color-secondary">{{ discussion.content }}</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </ScrollPanel>
                    </div>
                </div>
            </div>

            <!-- 右侧信息区域 -->
            <div class="col-12 lg:col-4">
                <div class="card">
                    <div class="mb-4">
                        <h5 class="mb-2">基本信息</h5>
                        <div class="field mb-3 flex flex-row gap-4">
                            <div class="flex-row flex gap-2 items-center">
                                <label for="questionBank" class="block font-bold ">所属题库</label>
                                <InputText  v-model="question.questionBankName" style="width: 32rem" placeholder="选择题库" />
                            </div>
                            <div class="flex-row flex gap-2 items-center">
                                <label for="questionBank" class="block font-bold">题库id</label>
                                <InputText v-model="question.questionBankId" class="" placeholder="选择题库" />
                            </div>
                        </div>

                        <div class="field mb-3">
                            <label for="url" class="block font-bold mb-2">url</label>
                            <InputText id="url" v-model="question.url" class="w-full"  />
                        </div>

                        <div class="field mb-3">
                            <label for="questionNumber" class="block font-bold mb-2">题目序号</label>
                            <InputNumber id="questionNumber" v-model="question.questionNumber" class="w-full" :min="1" />
                        </div>

                        <div class="field mb-3">
                            <label for="type" class="block font-bold mb-2">题目类型</label>
                            <Dropdown v-model="question.type" :options="questionTypes" optionLabel="label" optionValue="value" placeholder="选择类型" class="w-full" />
                        </div>

                        <div class="field mb-3">
                            <label for="status" class="block font-bold mb-2">状态</label>
                            <Dropdown v-model="question.status" :options="statusOptions" optionLabel="label" optionValue="value" placeholder="选择状态" class="w-full" />
                        </div>

                        <div class="field mb-3">
                            <label for="correctAnswer" class="block font-bold mb-2">正确答案</label>
                            <InputText v-model="question.correctAnswer" class="" placeholder="选择正确答案" />
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 删除确认对话框 -->
        <Dialog v-model:visible="deleteDialog" :style="{ width: '450px' }" header="确认删除" :modal="true">
            <div class="flex items-center gap-4">
                <i class="pi pi-exclamation-triangle !text-3xl" />
                <span>确定要删除这道题目吗？</span>
            </div>
            <template #footer>
                <Button label="取消" icon="pi pi-times" text @click="deleteDialog = false" />
                <Button label="确定" icon="pi pi-check" severity="danger" @click="deleteQuestion" />
            </template>
        </Dialog>
    </div>
</template>

<style scoped>
:deep(.p-scrollpanel) {
    border: 1px solid var(--surface-border);
    border-radius: 6px;
}

:deep(.p-scrollpanel-content) {
    padding: 1rem;
}

:deep(.p-avatar) {
    background-color: var(--primary-color);
    color: var(--primary-color-text);
}
</style>
